package com.loveyukari.utils;

import java.io.BufferedInputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


/**
*
*yangshaohua
*2017年1月6日下午5:49:26
**/
public class PinyinUtils {
	private static String url = "https://hanyu.baidu.com/s";
	
	public static String getPingyin(String str){
		StringBuilder sb = new StringBuilder();
		if (StringUtils.isNotBlank(str)){
			String[] split = str.split("");
			for (int i = 0; i < split.length; i++) {
				sb.append(getPinyinByChar(split[i])).append(" ");
			}
		}
		return sb.toString();
	}
	
	public static String getPinyinByChar(String c){
		try {
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("wd", c);
			HashMap<String, String> headers = new HashMap<>();
			headers.put("User-Agent","chrome");
			String res = HttpUtils.sendGet(url,params,headers);
			Document document = Jsoup.parse(res);
			Element pinyin = document.getElementById("pinyin");
			if (pinyin == null){
				return c;
			}
			Elements elements = pinyin.getElementsByTag("b");
			if (elements.size() == 0){
				return c;
			}
			if (elements.size() == 1){
				return elements.get(0).html();
			}
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < elements.size(); i++) {
				sb.append(elements.get(i).html()).append("/");
			}
			return sb.substring(0,sb.length()-1);
		} catch (Exception e) {
			return c;
		}
	}
	
}
